# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
每日任务拨打概况(欧派)
"""
import pymysql
from util import (
    logging,
    data2beautify,
    date_slice,
    query_es,
    ms2min,
    calc_percent,
    prefix_start_with,
    write_excel,
    db_ip,
    db_port,
    db_username,
    db_password,
    es_ip,
    es_port,
    excel_save_dir,
)


class ExportDailyTaskCallOverviewOP:
    def __init__(self, ui_data):
        self.data_date = ui_data["data_date"]
        self.business = ui_data.get("business")
        self.data_type = ui_data.get("data_type")
        self.call_type = ui_data.get("call_type")
        self.start_time = ui_data.get("start_time")
        self.end_time = ui_data.get("end_time")
        self.date_slice_result = date_slice(
            self.start_time, self.end_time
        )  # 将时间范围切片
        self.task_ids = ui_data.get("target_datas")
        company_id = ui_data.get("company_id")
        self.db_name = f"yicall_{company_id}"
        self.table_index = ui_data.get("business_id")
        self.conn = pymysql.connect(
            host=db_ip,
            port=db_port,
            user=db_username,
            passwd=db_password,
            charset="utf8",
        )
        self.cursor = self.conn.cursor()
        self.task_info = self.query_task_info()
        self.scene_info = self.query_scene_info()
        self.close_db()

    def query_task_info(self):
        """查询任务信息"""
        sql = f"""select task_id,task_name,target_count from {self.db_name}.b_{self.table_index}_callout_task;"""
        logging.info(f"查询{self.business}任务信息SQL:\n{sql}")
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        task_info = dict()
        if result:
            for x in result:
                task_id, task_name, import_count = x
                task_info[task_id] = {
                    "task_name": task_name,
                    "import_count": import_count,
                }
        logging.info(f"获取到{self.business}下的任务信息：\n{data2beautify(task_info)}")
        return task_info

    def query_scene_info(self):
        """查询场景信息"""
        sql = f"""select scene_id,scene_name from {self.db_name}.b_{self.table_index}_call_scene
        order by scene_id desc;"""
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        scene_info = {}
        if len(result) > 0:
            scene_info = {scene_id: scene_name for scene_id, scene_name in result}
        return scene_info

    def close_db(self):
        self.cursor.close()
        self.conn.close()

    def query_es_data(self, start_time, end_time):
        """查询呼出通话记录信息"""
        es_index = (
            f"{self.db_name}_{self.table_index}_callout_session_ach_{self.data_date}"
        )
        body = {
            "query": {
                "bool": {
                    "must": [
                        {
                            "range": {
                                "calloutFinishTime": {
                                    "gte": start_time,
                                    "lte": end_time,
                                }
                            }
                        }
                    ]
                }
            }
        }
        fields = [
            "taskId",
            "calloutConnectStatus",
            "dialogDuration",
            "dialogUserPrefer",
            "sceneId",
            "calloutLastNodeName",
        ]
        es_data = query_es(es_index, body, fields, es_ip, es_port)
        return es_data

    def handled_data(self):
        everyday_data = []
        for everyday in self.date_slice_result:
            start_time, end_time = everyday
            day_es_data = self.query_es_data(start_time, end_time)  # 查一天的数据
            dial_date = start_time[:10]  # 从开始时间中截取拨打日期
            one_day_data = {dial_date: {}}
            total_es_data = len(day_es_data)
            if total_es_data > 0:
                for es_data in day_es_data:
                    callout_connect_status = es_data.get("calloutConnectStatus")
                    if callout_connect_status == "100":  # 状态为100代表已接通
                        connected_num = 1
                        dialog_duration_ms = int(es_data.get("dialogDuration"))
                        dialog_duration_min = ms2min(dialog_duration_ms)
                    else:
                        connected_num = 0
                        dialog_duration_min = 0
                    task_id = int(es_data.get("taskId"))
                    task_name = self.task_info.get(task_id).get("task_name")
                    scene_id = int(es_data.get("sceneId"))
                    scene_name = self.scene_info.get(scene_id)
                    import_count = self.task_info.get(task_id).get(
                        "import_count"
                    )  # 名单数
                    user_prefer = es_data.get("dialogUserPrefer")  # 客户意向
                    if user_prefer == "A":
                        user_prefer_count = 1
                    else:
                        user_prefer_count = 0
                    hangup_node_name = es_data.get("calloutLastNodeName")  #  挂机节点
                    if prefix_start_with(hangup_node_name, ["1.1开场"]):
                        start_hangup_count = 1
                    else:
                        start_hangup_count = 0
                    find_task_name = one_day_data[dial_date].get(task_name, -1)
                    if find_task_name == -1:
                        one_day_data[dial_date][task_name] = {
                            "total_connected": connected_num,
                            "total_dialog_duration_min": dialog_duration_min,
                            "import_count": import_count,
                            "scene_name": scene_name,
                            "start_hangup_total": start_hangup_count,
                            "user_prefer_total": user_prefer_count,
                        }
                    else:
                        one_day_data[dial_date][task_name][
                            "total_connected"
                        ] += connected_num
                        one_day_data[dial_date][task_name][
                            "total_dialog_duration_min"
                        ] += dialog_duration_min
                        one_day_data[dial_date][task_name][
                            "start_hangup_total"
                        ] += start_hangup_count
                        one_day_data[dial_date][task_name][
                            "user_prefer_total"
                        ] += user_prefer_count
                everyday_data.append(one_day_data)
        logging.info(f"每日任务拨打概况：\n{data2beautify(everyday_data)}")
        return everyday_data

    def export(self):
        everyday_data = self.handled_data()
        if everyday_data:
            sheet_infos = []
            excel_title = [
                "外呼日期",
                "任务名",
                "所属场景",
                "名单量",
                "接通量",
                "接通率",
                "通话时长(分钟)",
                "A类",
                "接通意向率",
                "名单意向率",
                "开场挂断量",
                "开场挂断率",
            ]
            for one_day_data in everyday_data:
                dial_date = list(one_day_data.keys())[0]
                sheet_name = dial_date
                task_call_datas = list(one_day_data.values())[0]
                one_day_excel_data = []
                for task_name, task_call_data in task_call_datas.items():
                    import_count = task_call_data.get("import_count")
                    total_connected = task_call_data.get("total_connected")
                    connected_rate = calc_percent(total_connected, import_count, 2)
                    total_dialog_duration_min = task_call_data.get(
                        "total_dialog_duration_min"
                    )
                    scene_name = task_call_data.get("scene_name")
                    user_prefer_total = task_call_data.get("user_prefer_total")
                    connected_intent_rate = calc_percent(
                        user_prefer_total, total_connected, 2
                    )  # 接通意向率
                    import_intent_rate = calc_percent(
                        user_prefer_total, import_count, 2
                    )  # 名单意向率
                    start_hangup_total = task_call_data.get("start_hangup_total")
                    start_hangup_rate = calc_percent(
                        start_hangup_total, total_connected, 2
                    )  # 开场挂断率
                    one_day_excel_data.append(
                        [
                            dial_date,
                            task_name,
                            scene_name,
                            import_count,
                            total_connected,
                            connected_rate,
                            total_dialog_duration_min,
                            user_prefer_total,
                            connected_intent_rate,
                            import_intent_rate,
                            start_hangup_total,
                            start_hangup_rate,
                        ]
                    )
                sheet_infos.append([sheet_name, excel_title, one_day_excel_data])
            file_name = f"{self.business}_({self.call_type}){self.data_type}"
            excel_name = write_excel(sheet_infos, excel_save_dir, file_name)
            return {"code": 0, "excel_names": [excel_name], "msg": None}
        else:
            msg = (
                f"<font color=green>无法导出“{self.business}”的【{self.data_type}】，"
                f"原因：\n在{self.start_time}至{self.end_time}没有{self.call_type}数据！</font>"
            )
            return {"code": 1, "excel_names": None, "msg": msg}


if __name__ == "__main__":
    ...
